/**
 * 
 */
package com.etc.module.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.etc.common.exception.DataOperationException;
import com.etc.common.exception.SysOperationException;
import com.etc.common.util.CustomBeanUtils;
import com.etc.module.dao.IModuleMapper;
import com.etc.module.model.Module;
import com.etc.module.model.ModuleOper;
import com.etc.module.service.IModuleService;
import com.etc.module.vo.CheckTreeNode;
import com.etc.module.vo.ModuleVO;
import com.etc.module.vo.TreeNode;
import com.etc.user.service.impl.UserServiceImpl;
import com.github.pagehelper.PageHelper;

/**
 * @author Administrator
 *
 */
@Service("moduleService")
public class ModuleService implements IModuleService {

	Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

	@Autowired
	private IModuleMapper moduleMapper;

	@Override
	public Integer insert(ModuleVO vo) {
		int res = 0;
		Module module = new Module();
		try {
			CustomBeanUtils.copyProperties(module, vo);
			res = moduleMapper.insert(module);
		} catch (Exception e) {
			String errMsg = String.format("module保存异常,参数 :vo=%s", vo);
			log.error(errMsg, e);
			throw new DataOperationException(errMsg);
		}
		return res;
	}

	@Override
	public void delete(Integer id) {
		try {
			moduleMapper.delete(id);
		} catch (Exception e) {
			String errMsg = String.format("module删除异常,参数:id=%s", id);
			log.error(errMsg, e);
			throw new DataOperationException(errMsg);
		}
	}

	@Override
	public void update(ModuleVO vo) {
		Module module = new Module();
		try {
			CustomBeanUtils.copyProperties(module, vo);
			moduleMapper.update(module);
		} catch (Exception e) {
			String errMsg = String.format("module修改异常,参数:vo=%s", vo);
			log.error(errMsg, e);
			throw new DataOperationException(errMsg);
		}
	}

	@Override
	public ModuleVO selectById(Integer id) {
		ModuleVO moduleVO = new ModuleVO();
		try {
			Module module = moduleMapper.selectById(id);
			CustomBeanUtils.copyProperties(moduleVO, module);
		} catch (Exception e) {
			String errMsg = String.format("module查询异常,参数:id=%s", id);
			log.error(errMsg, e);
			throw new SysOperationException(errMsg);
		}
		return moduleVO;
	}

	@Override
	public List<ModuleVO> list(Map<String, Object> param) {
		try {
			PageHelper.startPage((Integer) param.get("pageNo"), (Integer) param.get("pageNum"));
			List<Module> modelList = moduleMapper.list(param);
			List<ModuleVO> voList = new ArrayList<ModuleVO>();

			for (Module model : modelList) {
				ModuleVO vo = new ModuleVO();
				CustomBeanUtils.copyProperties(vo, model);
				voList.add(vo);
			}
			return voList;
		} catch (Exception e) {
			String errMsg = String.format("查询异常,参数 :param=%s", param);
			log.error(errMsg, e);
			throw new SysOperationException(errMsg);
		}
	}

	@Override
	public int count(Map<String, Object> param) {
		return moduleMapper.count(param);
	}

	@Override
	public List<ModuleVO> findChildModuleByParentId(Integer parentId) {
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("tsmParentId", parentId);
			param.put("tsmStatus", 1);
			List<Module> modelList = moduleMapper.list(param);
			List<ModuleVO> voList = new ArrayList<ModuleVO>();
			for (Module model : modelList) {
				ModuleVO vo = new ModuleVO();
				CustomBeanUtils.copyProperties(vo, model);
				voList.add(vo);
			}
			return voList;
		} catch (Exception e) {
			String errMsg = String.format("查询异常,参数 :param=%s", parentId);
			log.error(errMsg, e);
			throw new SysOperationException(errMsg);
		}
	}
	
	@Override
	public TreeNode findTreeMenu(Integer parentId) {
		Module targetMenu = moduleMapper.selectById(parentId);

		TreeNode targetNode = new TreeNode();
		targetNode.setId(targetMenu.getTsmId());
		targetNode.setLeaf(targetMenu.getTsmIsLeaf() == 0 ? false : true);
		targetNode.setText(targetMenu.getTsmName());
		targetNode.setUrl(targetMenu.getTsmUrl());
		targetNode.setIconCls(targetMenu.getTsmIcon());
		
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("tsmParentId", parentId);
		param.put("tsmStatus", 1);
		List<Module> menus =moduleMapper.list(param);
		if (menus.size() > 0) {
			List<TreeNode> children = new ArrayList<TreeNode>();
			for (Module menu : menus) {
				TreeNode node = new TreeNode();
				node.setId(menu.getTsmId());
				node.setLeaf(menu.getTsmIsLeaf() == 0 ? false : true);
				node.setText(menu.getTsmName());
				node.setUrl(menu.getTsmUrl());
				node.setIconCls(menu.getTsmIcon());
				children.add(findTreeMenu(node.getId()));
			}
			targetNode.setChildren(children);
		}
		return targetNode;
	}

    @Override
    public CheckTreeNode findModuleByRoleId(Integer id,Integer roleId) {
        Module targetModule = moduleMapper.selectById(id);
        CheckTreeNode targetNode=moduleToNode(targetModule);
        if(targetNode.getLeaf()){
            targetNode.setLeaf(false);
            targetNode.setExpanded(true);
            Map<String, Object> param=new HashMap<>();
            param.put("tsmId", id);
            List<Module> modules=moduleMapper.listModuleOperation(param);
            List<ModuleOper> roleOperationList=new ArrayList<>();
            //如果用户角色id不为空，则获取角色配置的功能权限，并权限全集中进行匹配
            if(roleId!=null){
                param.put("tsrId", roleId);
                List<Module> roleModules=moduleMapper.listModuleOperation(param);
                if(!CollectionUtils.isEmpty(roleModules)){
                    roleOperationList=roleModules.get(0).getOperations();
                }
            }
            List<ModuleOper> operationList=modules.get(0).getOperations();
            List<CheckTreeNode> list=new ArrayList<>();
            for(ModuleOper oper:operationList){
            	CheckTreeNode operNode=new CheckTreeNode();
            	operNode.setChildren(null);
            	operNode.setId(oper.getTmroId());
            	operNode.setExpanded(false);
            	operNode.setChecked(false);
            	if(!CollectionUtils.isEmpty(roleOperationList)&&roleOperationList.contains(oper)){
            	    operNode.setChecked(true);
            	}
            	operNode.setLeaf(true);
            	operNode.setText(oper.getOperation().getTsoName());
            	list.add(operNode);
            }
            targetNode.setChildren(list);
        }
        
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("tsmParentId", id);
        param.put("tsmStatus", 1);
        List<Module> modules =moduleMapper.list(param);
        if(modules.size()>0){
            List<CheckTreeNode> children=new ArrayList<>();
            for(Module module:modules){
                CheckTreeNode childNode=moduleToNode(module);
                children.add(findModuleByRoleId(childNode.getId(),roleId));
            }
            targetNode.setChildren(children);
        }
        return targetNode;
    }
    
    private CheckTreeNode moduleToNode(Module module){
        CheckTreeNode node=new CheckTreeNode();
        node.setChecked(null);
        node.setIconCls(module.getTsmIcon());
        node.setId(module.getTsmId());
        node.setExpanded(true);
        node.setLeaf(module.getTsmIsLeaf()==0?false:true);
        node.setText(module.getTsmName());
        return node;
    }

    

}
